<template>
	<mainHeader :title="mainHeaderTitle" :haveBack="true" goto="back"></mainHeader>
	<scroll-view scroll-y class="header_scroll">
		<view class="addPopup">
			<view class="addClass">
				<view class="addClass_top">
					<scroll-view scroll-x class="addClass_main_box">
						<view class="addClass_main">
							<view class="addClass_main_one " @click="newAddOne.showClass=item.data"
								:class="newAddOne.showClass==item.data?'addClass_main_one_active':''"
								v-for="(item,index) in addClassMain" :key="item">
								{{item.title}}
							</view>
						</view>
					</scroll-view>
					<addClassPopupVue>
						<view class="addClass_add ">
							添加标签
						</view>
					</addClassPopupVue>
				</view>
				<scroll-view class="addClass_one_box" scroll-y>
					<view class="addClass_one">
						<view class="addClass_one_list">
							<view class="addClass_one_list_one oneLine" @click="newAddOne.showOne=item"
								@longpress="deleteClass(item,newAddOne.showClass)"
								:class="newAddOne.showOne==item?'addClass_one_list_one_active':''"
								v-for="(item,index) in addClassOne[newAddOne.showClass]" :key="item">
								{{item}}
							</view>
							<!-- 填充 -->
							<view class="addClass_one_list_one" v-for="item in 5"  :key="item" style="opacity: 0;">占格</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="addTool" :style="'background:'+store.state.theme">
				<view class="addInputBox">
					<view class="addTool_input">
						<view class="addTool_money">{{moneySymbol}}</view>
						{{newAddOne.addValue}}
					</view>
					<view class="addTool_input_newAdd">{{newAdd}}</view>
					<image class="addTool_icon" src="@/static/add/expenses-one.png" @click="clearOver()" v-if="newAddOne.showClass==addClassMain[0].data"></image>
					<image class="addTool_icon" src="@/static/add/income-one.png" @click="clearOver()" v-else></image>
				</view>
				<view class="addInputNotes">
					<image class="addInputNotes_input_icon" src="@/static/add/writing-fluently.png"></image>
					<textarea class="addInputNotes_input" v-model="newAddOne.notesValue" auto-height
						v-if="inputArea"></textarea>
					<input class="addInputNotes_input" v-model="newAddOne.notesValue" type="text" placeholder="备注"
						v-else></input>
					<image class="addInputNotes_input_clear" src="@/static/base/delete-three.png"
						v-show="newAddOne.notesValue!=''" @click="newAddOne.notesValue=''"></image>
				</view>
				<uni-datetime-picker style="flex: 0;width: max-content;" v-model="newAddOne.timeValue" type="date">
					<view class="chooseTime">
						<image class="chooseTime_icon" src="@/static/add/calendar.png"></image>
						<view class="chooseTime_text">
							{{newAddOne.timeValue}}
						</view>
					</view>
				</uni-datetime-picker>
				<view class="addKeyboard">
					<view class="addKeyboard_one clickBox" @click="KeyboardClick(item)" v-for="item in keyBoardData" :key="item">
						{{item}}
					</view>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script setup>
	import addClassPopupVue from "./addClassPopup.vue";
	import {
		dateTypeFormat,
		myShowToast,
		reLoading
	} from "@/uitls/tool.js"
	import {
		ref,
		computed
	} from 'vue'
	import store from '@/store/index.js';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	const allData = computed(() => store.state.mainData.allData)
	const inputArea = computed(() => store.state.setting.inputArea)
	const moneySymbol = computed(() => store.state.setting.MoneySymbol)
	const {
		addClassMain,
		addClassOne
	} = store.state.AddClass
	const newAddOne = ref({
		showClass: 0,
		showOne: addClassOne[0][0],
		addValue: "0",
		notesValue: '',
		timeValue: store.state.indexShowTime || dateTypeFormat('YYYY-mm-dd', new Date())
	})
	const mainHeaderTitle = ref("添加记录")
	const deleteClass = (className, classTag) => {
		let tag = classTag == 0 ? '支出' : '收入'
		uni.showModal({
			title: '提示',
			content: `确定要删除${tag}分类的${className}标签吗`,
			success: function(res) {
				if (res.confirm) {
					store.commit("AddClass/delAddClassOne", {
						className,
						classTag
					})
					myShowToast(`${className}标签删除成功`)
				} else if (res.cancel) {}
			}
		});
	}
	const theOne = ref() // 判读 添加/修改
	const props = defineProps({ // 页面传值
		theMonth: String,
		theMonthIndex: String
	})
	onLoad((e) => {
		if (Object.keys(e).length != 0 ) {
			mainHeaderTitle.value = "修改记录"
			theOne.value = allData.value[props.theMonth][props.theMonthIndex]
			newAddOne.value = JSON.parse(JSON.stringify(theOne.value))
		}
	})
	const keyBoardData = ref(['1', '2', '3', '删除', '4', '5', '6', '+', '7', '8', '9', '-', '再记', '0', '.', '完成'])
	const newAdd = ref(null) // 金额 输入框中显示 中间值
	const KeyboardClick = (x) => {
		const isToLong = (x) => {
			if (x.length > 10) {
				myShowToast('数字过长')
				return true
			}
			return false
		}
		const addOhter = (tag) => {
			// 分离最后的运算符和其他部分  
			let endOperator = other.slice(-1);
			let oldValue = other.slice(0, -1);
			let oldNum = parseFloat(oldValue);
			let addNum = parseFloat(newAddOne.value.addValue);

			// 根据运算符计算新值  
			other = endOperator === '+' ? oldNum + addNum : oldNum - addNum;
			let maxLengthAfterDecimal = Math.max(
				(oldValue.indexOf(".") !== -1) ? oldValue.length - oldValue.indexOf(".") - 1 : 0,
				(newAddOne.value.addValue.indexOf(".") !== -1) ? newAddOne.value.addValue.length - newAddOne
				.value.addValue.indexOf(".") - 1 : 0
			);
			newAdd.value = other.toFixed(maxLengthAfterDecimal) + (tag || '');
		}
		const Todot2 = (x) => { // 保留2位小数 不四舍五入
			let dot = x.indexOf(".")
			if (dot == -1) return x
			else return x.substring(0, dot + 3)
		}
		const over = () => {
			let showToastText = theOne.value ? '修改记录成功' : '添加记录成功'
			myShowToast(showToastText, {
				position: "bottom",
				icon: "success",
			})
			if (theOne.value) {
				store.commit("mainData/chanegAllData", {
					oldData: theOne.value,
					newData: JSON.parse(JSON.stringify(newAddOne.value))
				})
				setTimeout(() => {
					uni.switchTab({
						url: "/pages/index/index"
					})
					// reLoading()
				}, 500)
			} else {
				store.commit("mainData/addAllData", JSON.parse(JSON.stringify(newAddOne.value)))
				if (x == "完成") {
					setTimeout(() => {
						uni.navigateBack()
						// reLoading()
					}, 500)
				}
			}
			clearOver()
		}
		let addValue = newAddOne.value.addValue
		let other = newAdd.value
		if (x >= 0) {
			if (addValue.length == 1 && parseFloat(addValue) == 0) {
				newAddOne.value.addValue = x.toString();
			} else {
				if (isToLong(addValue)) return;
				newAddOne.value.addValue += x.toString();
			}
		} else if (x == '.') {
			if (isToLong(addValue)) return;
			if (addValue.indexOf(".") == -1) {
				newAddOne.value.addValue += x
			}
		} else if (x === '+' || x === '-') {
			// 处理加减运算  
			if (parseFloat(addValue) == 0 && addValue.length == 1 || newAddOne.value.addValue == "-") {
				newAddOne.value.addValue = "-"
			} else if (parseFloat(addValue) !== 0) {
				if (other === null) {
					// 第一次输入  
					addValue += x;
					newAdd.value = addValue;
					newAddOne.value.addValue = "0";
				} else {
					addOther(x);
					newAddOne.value.addValue = "0";
				}
			}
		} else if (x == "删除") {
			if (addValue.length > 1) {
				newAddOne.value.addValue = addValue.slice(0, -1)
			} else if (addValue.length == 1) {
				if (addValue !== "0") {
					newAddOne.value.addValue = "0";
				} else if (other !== null) {
					newAdd.value = null;
				}
			}
		} else if (x == "再记" || x == "完成") {
			if (other != null) {
				addOhter("")
				newAddOne.value.addValue = parseFloat(other) + ""
				newAdd.value = null
			} else {
				newAddOne.value.addValue = Todot2(newAddOne.value.addValue)
				if (parseFloat(addValue) < 0) {
					myShowToast('不可将金额设置为负数')
				} else if (parseFloat(addValue) < 0.01) {
					uni.showModal({
						title: '提示',
						content: "您设置的金额将为零",
						success: function(res) {
							if (res.confirm) {
								over()
							} else if (res.cancel) {}
						}
					});
					newAddOne.value.addValue = "0"
				} else {
					over()
				}
			}
		}
	}
	const clearOver = () => {
		newAdd.value = null
		newAddOne.value.addValue = "0"
		newAddOne.value.notesValue = ""
	}
</script>
<style lang="scss" scoped>
	@import "@/style/base.scss";

	.addPopup {
		width: 100%;
		min-height: calc(100vh - var(--status-bar-height) - 2em);
		border-radius: 10px 10px 0 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.addClass {
			padding: 0.5em;
			display: flex;
			flex-direction: column;
			flex: 1;

			.addClass_top {
				display: flex;
				justify-content: space-between;

				.addClass_main_box {
					width: 80%;

					.addClass_main {
						display: flex;
						align-items: center;

						.addClass_main_one {
							flex: 0;
							white-space: nowrap;
							font-weight: bold;
							margin: 0 0.2em;
							padding-bottom: 0.15em;
							transition: $baseTransition, background-size 0.2s;
							background: linear-gradient(to right, $baseColor, $baseColor) no-repeat;
							background-position: bottom;
							background-size: 0px 0.1em;
							font-size: $bigFontsize;

							&_active {
								color: $baseColor;
								background-size: 100% 0.1em;
							}
						}
					}
				}

				.addClass_add {
					flex-shrink: 0;
					margin: 0 0.2em;
					padding: 0.15em;
					white-space: nowrap;
					font-weight: bold;
					color: $baseColor_mid;

					&:active {
						color: $baseColor;
					}
				}
			}

			.addClass_one_box {
				flex: 1;
				margin-top: 0.3em;
				max-height:40vh;
				.addClass_one {
					
					.addClass_one_list {
						display: flex;
						justify-content: space-around;
						align-items: center;
						flex-wrap: wrap;

						&_one {
							margin: 0.2em;
							text-align: center;
							font-size: $bigFontsize;
							padding: 0.2em 0.5em;
							border: $baseColorBorder;
							border-radius: 0.1em;
							color: $baseBlack_mid;

							&:last-child {
								margin-right: auto;
							}
								
							&_active {
								background: $baseColor;
								color: $baseWhite;
							}
						}
					}
				}
			}
		}

		.addTool {
			flex-shrink: 0;
			border-top: $baseColorBorder;
			border-radius: 1em 1em 0 0;
			display: flex;
			flex-direction: column;
			width: 100%;
			padding: 0.5em;

			.addInputBox {
				display: flex;
				border: $baseBorder;
				border-radius: 0.5em;
				position: relative;

				&:focus-within {
					border: $baseColorBorder;
				}

				.addTool_input {
					height: 2.5em;
					max-width: calc(100% - $iconSize_base - 0.5em);
					overflow: hidden;
					display: flex;
					justify-content: end;
					align-items: center;
					font-size: $bigFontsize;
					position: relative;
					transition: $baseTransition;
					
					.addTool_money {
						margin: 0 0.5em;
						font-size: $smallFontsize;
						color: $baseBlack_big;
					}
				}

				.addTool_input_newAdd {
					position: absolute;
					left: 1em;
					top: -0.1em;
					font-size: $smallFontsize;
					color: $baseColor_mid;
				}

				.addTool_icon {
					position: absolute;
					right: 0;
					top: 50%;
					transform: translate(-25%, -50%);
					width: $iconSize_base;
					height: $iconSize_base;
				}
			}

			.addInputNotes {
				border-bottom: $baseBorder;
				margin: 0.5em;
				position: relative;
				display: flex;
				justify-content: space-between;

				&:focus-within {
					border-bottom: $baseColorBorder;
				}

				.addInputNotes_input {
					margin: 0 0.5em;
					flex: 1;
					color: $baseBlack_mid;
					font-size: $midFontsize;
				}

				.addInputNotes_input_clear,
				.addInputNotes_input_icon {
					margin-top: 0.1em;
					width: $iconSize_small;
					height: $iconSize_small;
				}
			}

			.chooseTime {
				display: flex;
				align-items: center;

				// margin: 0.1em 0;
				.chooseTime_icon {
					width: $iconSize_small;
					height: $iconSize_small;
				}

				.chooseTime_text {
					padding: 0.3em;
					font-size: $midFontsize;
					color: $baseBlack_mid;
				}
			}

			.addKeyboard {
				flex: 1;
				display: grid;
				grid-template-columns: 1fr 1fr 1fr 1fr;
				grid-template-rows: 1fr 1fr 1fr 1fr;
				grid-gap: 0.3em 0.5em;

				.addKeyboard_one {
					width: 100%;
					height: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: $bigFontsize;
					line-height: 2.5em;
					border-radius: 0.5em;
					&:active {
						color: $baseColor_mid;
					}

					&:last-child {
						color: $baseColor_mid;
						font-weight: bold;
					}
				}
			}
		}
	}
</style>